/*
 * simplelightbox.js - A minimal, unobtrusive javascript lightbox engine for 
 * easily highlighting images in web pages (no libraries required)
 *
 * This program is free software - you are free to use it however you want.
 * For more information, look up the GNU GPL.
 *
 * Authored by Vitor Sonoki - http://sonokisworld.appspot.com
 *
 * version: 0.8
 */
'use strict';

// This global variable counts all the pictures that 
var index = 0;

// This is a class that applies the functionality to the images in this page.
function Picture(image) {
    image.onclick = function() {
        showHighlights(image);
    }
    image.style.cursor = "pointer";
    
    // set a Token to state which picture index this is.
    image.index = index;
    index++;
}

function showHighlights(image) {
    // Counting token:
    var index = image.index
    
    var realestate = {
        width: window.innerWidth,
        height: window.innerHeight
    };
    
    var shade = document.createElement("div");
    shade.style.background = "rgba(0,0,0,0.8)";
    shade.style.zIndex = "97";
    shade.style.position = "fixed";
    shade.style.top = "0px";
    shade.style.left = "0px";
    shade.style.width = "100%";
    shade.style.height = "100%";
    
    // Changed on v0.7: now we're packaging a counter saying how many more
    // pictures are left (ex: 1/4, 3/15, 2/5...)
    var imgCounter = document.createElement('div');
    
    // Changed on v0.8: we will include a counter and a legend extracted from "alt"
    // counter goes on top of the picture, legend on the bottom.
    var legend = document.createElement('div');
    
    imgCounter.style.fontSize =  legend.style.fontSize =    "20px";
    imgCounter.style.width =     legend.style.width =       "100%";
    imgCounter.style.zIndex =    legend.style.zIndex =        "98";
    imgCounter.style.textAlign = legend.style.textAlign = "center";
    imgCounter.style.position =  legend.style.position =   "fixed";
    imgCounter.style.color =     legend.style.color =       "#FFF";
    imgCounter.style.left =      legend.style.left =           "0";    
    
    // The picture we're currently showing:
    var highlight = document.createElement('img');
    highlight.src = image.src;
    highlight.style.maxHeight = "84%";
    highlight.style.maxWidth = "92%";
    highlight.style.zIndex = "99";
    highlight.style.position = "fixed";
    highlight.style.margin = highlight.style.padding = "0";
    highlight.style.border = "4px solid white";
    highlight.style.display = "block";
    if (!(window.index === 0)) {
        highlight.style.cursor = "pointer";
    }
    
    // Base64 for maximum portability!
    var closebutton = document.createElement('div');
    closebutton.style.width = "30px";
    closebutton.style.height = "30px";
    closebutton.style.backgroundImage = "url('data:image/png; base64, iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA7MK6iAAAAAXNSR0IArs4c6QAAAAZiS0dEALwAGgAawKeBtgAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB90LDgAzEBynlicAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAADKElEQVRIx8WXTUgbURCAv7dNav1FwcZDFZsItmBugnSDIIigBw/m4MWeWqWXFoVAKUh7sggi5FDaS8H2VK/2kEMDIgiSiGBPBlrBBKkFsxQsqcZaQ18P7i6bdVdj/zK395id782beTOzghJFSjkE9AGdQBtwFSgAe8AWsA4sCiHe8qcipayRUk5JKbOydMnq39T8LvTOBYFOB7jjZl+4QJ8D9617+XSabCzG12SSg81NjnZ3ER4PlxsbqW5vp15VaRocpCoQsJt7IYR4cC5YSvkGGLEC09Eo2YWFkm6qKRwmEInYDzAvhLjtCrZ7+nl+no+Tk8jj4wuFSXi93Jie5trIiKvnwhpT4JWxzjx7RnpmBk9dHQCFXO7CeRJ49Aj/+Lh1664Q4rUJ1jNwC/AZnn54+JCajg6u9vdzpbmZT3Nz7KdS58LqVZWvyaS5vjk7a/VcA9qEEPsGeAp4bMR0tbeXS5WVtIyNcX1iAsXj4UjTWO3pOdPzrnic2mCQvUSC98PD5rXfWlqyxvypEOKJoi/uGbvpaNSM6ZXmZhSPB4AKn4+ud+9coerKCrXBIAANoRD1qnoSwuNj0tGoVfUegKJXJJ/5ZPTsLeRyfJqb40jTzC8qW1tRV1YcoVV+v7n+trFRdN3ZhQXy6bSx9EkphxS9DJ4oxGJFBvdTKVZ7ejjc3jb3qvz+Irgdms9kWOvvP3U4m+0+Ra+9AEWnNKSQy5EIhchnMqfgTtBkd7djKGy2OxW94ANwsLnpGsNkd/cpeKlQB9ttCtBgrH58+XLmU7HDS4U62G5QKJMoej8F4HJj45nK9pi6JZyT2GzvKXrFAqC6vb1kaD6TcUw4N7HZ3lL0ycEsd3bx1NURSiQcE8kp4dzgNtvrCrBotrTBwSLlmo4Obi0vU9na6ppIpcJtthcVfUbSAKoCAZrCYdPTltFRKnw+U/twe9sxe53gXfF4UY+21GpNCPHWyOqXZiuLRBBeLwDfd3b4WSgAcKRprA0MlPzUaoNB6lUV4fUSiESsqi//SVu0d6gz2+LfHgSMnnzuIFDW0aesw97/HG/LNtCX7RdGlOun7RfiVqZ/N/SVbwAAAABJRU5ErkJggg==')";
    closebutton.style.position = "fixed";
    closebutton.style.zIndex = "100";
    closebutton.style.cursor = "pointer";
    
    document.body.appendChild(shade);
    document.body.appendChild(highlight);
    document.body.appendChild(closebutton);
    document.body.appendChild(imgCounter);
    document.body.appendChild(legend);
    
    // get full dimensions of the pictures:
    var dimensions = {
        width: highlight.clientWidth,
        height: highlight.clientHeight
    };
    
    // Positioning like a bawce
    highlight.style.top = (((realestate.height - dimensions.height) / 2) - 15).toString() + "px";
    highlight.style.left = ((realestate.width - dimensions.width) / 2).toString() + "px";
    imgCounter.style.top = (parseInt(highlight.style.top) - 30).toString() + "px";
    legend.style.bottom = (parseInt(highlight.style.top) - 15).toString() + "px";
    imgCounter.innerHTML = (index + 1) + " / " + window.index;
    legend.innerHTML = image.alt
    
    // Position the close button just right:
    closebutton.style.top = (parseInt(highlight.style.top) - 14) + "px";
    closebutton.style.left = (parseInt(highlight.style.left) + dimensions.width - 8) + "px";
    
    function closeLightbox() {
        try {
            document.body.removeChild(highlight);
            document.body.removeChild(shade);
            document.body.removeChild(closebutton);
            document.body.removeChild(imgCounter);
            document.body.removeChild(legend);
            return true;
        }
        catch(NotFoundError) {
            return false;
        }
    }
    
    function nextImage() {
        if (window.index == 0) return;
        
        if (index < window.index -1) { // If this is false, we are on the last guy.
            closeLightbox();
            showHighlights(slbPics[index + 1]);
        }
        else {
            closeLightbox();
            showHighlights(slbPics[0]);
        }
    }
    
    function prevImage() {
        if (window.index == 0) return;
        
        if (index > 0) { // As long as not the first guy...
            closeLightbox();
            showHighlights(slbPics[index - 1]);
        }
        else {
            closeLightbox();
            showHighlights(slbPics[window.index - 1]);
        }
    }
    
    /*
     * Keyboard shortcuts defined to improve navigation:
     *
     * -ESC: quits simplelightbox, goes back to normal page view.
     * -SPACE: goes to the next image in the list.
     * -RIGHT ARROW: same as space.
     * -LEFT ARROW: inverse of space - goes to the previous image.
     */
    if (window.addEventListener) {
        window.addEventListener("keydown", function(e) {
            if (e.keyCode == 27) {
                closeLightbox();
            }
            else if (e.keyCode == 32 || e.keyCode == 39) {
                if (closeLightbox()) {
                    nextImage();
                }
            }
            else if (e.keyCode == 37) {
                if (closeLightbox()) {
                    prevImage();
                }
            }
        });
    } else if (window.attachEvent) {
        window.attachEvent("onkeydown", function(e) {
            if (e.keyCode == 27) {
                closeLightbox();
            }
            else if (e.keyCode == 32) {
                if (closeLightbox()) {
                    nextImage();
                }
            }
            else if (e.keyCode == 37 || e.keyCode == 39) {
                if (closeLightbox()) {
                    prevImage();
                }
            }
        });
    }
    
    highlight.onclick = function() {
        nextImage();
    }
    shade.onclick = closebutton.onclick = function() {
        closeLightbox();
    }
}

// the kickstarter!
function slbInitialize() {
    window.slbPics = document.querySelectorAll('img.slbPhoto');
    if (window.slbPics.length === 0) {
        window.slbPics = document.querySelectorAll("img");
    }
    for (var i = 0; i < slbPics.length; i++) {
        var a = new Picture(slbPics[i]);
    }
}